# -*- coding: utf-8 -*-
from re import L
import sys
import os
import io
from os import path as osp

import json
import requests
import base64
import shutil
import cv2
import numpy as np
from tqdm import tqdm
from PIL import Image

from tool import filesystem


class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, bytes):
            return obj.decode("utf-8")
        else:
            return super(MyEncoder, self).default(obj)


def post_cls(img_b64):
    data = {
        "img_b64": img_b64,
        # 1 WeatherDetection cls

        "mdl_idx": 1,
        "algo_type": "WeatherDetection",
        "mdl_type": "cls"
    }

    url = "http://192.168.200.125:9999/api/rec"
    headers = {'Content-Type': 'application/json;charset=UTF-8'}
    string = json.dumps(data, cls=MyEncoder)
    r = requests.post(url, data=string, headers=headers)
    cls_data = r.json()
    if cls_data["code"] != 0: 
        return None
    return cls_data


def http2via(file_path):
    """图片检测"""
    one_data = {}
    if not osp.exists(file_path):
        return None
    
    file_size = osp.getsize(file_path)
    filename = osp.basename(file_path)
    one_data["filename"] = filename
    one_data["size"] = file_size
    one_data["file_attributes"] = {}

    buffer = io.BytesIO()
    img = cv2.imread(file_path)
    rgb_img = img[:, :, :: -1]
    pil_image = Image.fromarray(rgb_img)
    pil_image.save(buffer, format="jpeg")
    encoded = base64.b64encode(buffer.getvalue())
    data = post_cls(encoded)
    # print(data['category'])
    
    return data['category']


def distribute(sub_dir, save_dir, data_dict):
    # 检测图片复制到新的文件夹

    for f, v in data_dict.items():
        target = osp.join(sub_dir, f)

        files = osp.split("_")
        save = osp.join(save_dirs, files[0], files[1], v[0])
        if not osp.exists(save):
            os.makedirs(save, exist_ok = True)
        
        shutil.copy(target, save)
        

    y = sub_dir[-3]
    m = sub_dir[-2]

    save_dirs = osp.join(save_dir, y, m)

def weatherDetect(data_dir, save_dir):
    """天气检测"""
    sub_dirs = filesystem.get_last_dir(data_dir, -1)

    for sub_dir in sub_dirs:
        imgs = filesystem.get_all_filepath(sub_dir)
        if len(imgs) == 0:
            print("continue:", sub_dir)
        
        print(sub_dir)
        save_dicts = {}
        for f in tqdm(imgs):
            one_data = http2via(f)

            level_one = osp.basename(f).split("_")[0]  # year
            level_two = osp.basename(f).split("_")[1]  # month
            det = 'weather'
            if level_one == "norm1":
                # 对norm1增设一级目录
                save_path = osp.join(save_dir, det, f.split("\\")[-5], level_two, level_one, one_data)
            else:
                save_path = osp.join(save_dir, det, level_one, level_two, one_data)

            if not osp.exists(save_path):
                os.makedirs(save_path)
            
            shutil.copy(f, osp.join(save_path, osp.basename(f)))
        

def main():
    data_dir = r"F:\work\code\paddle\train_data\cls\weather\images"
    save_dir = r"F:\work\code\paddle\train_data\det"
    # data_dir = sys.argv[1]
    # save_dir = sys.argv[2]
    data = weatherDetect(data_dir, save_dir)
    # distribute(osp.dirname(data_dir, save_dir, data)


if __name__ == "__main__":
    main()